
//
//  CLComposeViewController.swift
//  CLWeibo
//
//  Created by 陈亮 on 16/7/18.
//  Copyright © 2016年 陈亮. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage

class CLComposeViewController: UIViewController {

    // MARK:  懒加载控件
    private lazy var titleLabel:UILabel = {
    
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 17)
        label.numberOfLines = 0
        label.textAlignment = .Center
        //获取中间用户名
        if let name = CLUserAccountViewModel.sharedUserAccount.userAccount?.name {
            
            let title = "发微博\n\(name)"
            let attributeStr = NSMutableAttributedString(string: title)
            //截取名字的范围
            let range = (title as NSString).rangeOfString(name)
            attributeStr.addAttributes([NSForegroundColorAttributeName:UIColor.lightGrayColor(),NSFontAttributeName:UIFont.systemFontOfSize(12)], range: range)
            label.attributedText = attributeStr
        } else {
            label.text = "发微博"
        }
        //设置大小
        label.sizeToFit()
        return label
    }()
    
    //右侧按钮
    private lazy var rightButton:UIButton = {
    
        let button = UIButton()
        
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        button.setTitle("发送", forState: .Normal)
        button.addTarget(self, action: "sendWeiboAction", forControlEvents: .TouchUpInside)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.setTitleColor(UIColor.grayColor(), forState: .Normal)
        button.size = CGSize(width: 45, height: 30)
        return button
    }()
//    添加自定义的textView
    private lazy var textView: CLComposeTextView = {
        let view = CLComposeTextView()
        view.delegate = self
        view.placeHolder = "请输入微博文字"
        view.font = UIFont.systemFontOfSize(14)
        //开启弹簧效果
        view.alwaysBounceVertical = true
        return view
    
    }()
    
    //toolbar
    private lazy var toolBar:CLComposeToolBar = {
    
        let view = CLComposeToolBar(frame: CGRectZero)
        return  view
        
    }()
    //配图
    private lazy var pictureView:CLComposePictureView = {
    
        let view = CLComposePictureView()
        return view
    }()
    //表情键盘
    private lazy var keyboard:CLEmoiconKeyBoard = {
    
        let view = CLEmoiconKeyBoard()
        view.size = CGSize(width: self.textView.width, height: 216)
        return view
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setUpUI()
    }
    //
   

    //设置界面
    private func setUpUI(){
        //监听键盘改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //监听表情按钮的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectedEmoicon:", name:DidSelecteEmoticonNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deletedButton", name: DidSelecteDeleteButtonNotification, object: nil)
        setUpNavUI()
        //添加控件
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(self.toolBar.snp_top)
        }
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(30)
        }
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.leading.equalTo(textView).offset(10)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }
        
        //设置闭包
        toolBar.selectedToolBarButtonClosure = {[weak self](type :CLComeposeToolBarButtonType) in

            switch type {
            case .Picture:
                print("图片")
                self?.didSelectedPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("话题")
            case .Emoticon:
                print("表情")
                self?.didSelectedEmoicon()
            case .Add:
                print("添加")
            }
            
        
        
        }
        pictureView.didSelectedAddClosure = { [weak self] in
            
            self?.didSelectedPicture()
            
        }
        
    }
    
    private func setUpNavUI(){
        
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
   // MARK:  监听键盘frame改变
    @objc private func keyboardChangeFrame(noti:NSNotification){
        
        //获取屏幕的Frame
        let keyboardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //获取动画时长
        let duration = (noti.userInfo! [UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        //更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - ScreenHeight)
        }
        //执行动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    // MARK:  监听表情按钮的通知
    @objc private func selectedEmoicon(noti:NSNotification) {
        let emoicon = noti.object! as! CLEmoiconModel
        
        textView.insertEmoicon(emoicon)

        //如果是默认和浪小花表情
//        if emoicon.type == "0" {
//            //定义属性 记录并保存上一次点击的表情
//            let originalAttributedStr = NSMutableAttributedString(attributedString: textView.attributedText)
//            //获取表情按钮对应的图片
//            let image = UIImage(named: emoicon.path!)
//            //定义属性 文本附件
//            let attachment = NSTextAttachment()
//            //将图片的是属性赋值给文本附件
//            attachment.image = image
//            //获取行高 设置与文本一致
//            let fontHeight = textView.font!.lineHeight
//            //设置富文本大小
//            attachment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
//            //通过文本附件 创建富文本
//            let attributedStr = NSAttributedString(attachment: attachment)
//            //追加富文本
////            originalAttributedStr.appendAttributedString(attributedStr)
//            //设置替换选择的范围
//            var range = textView.selectedRange
//            //根据指定范围  设置替换的富文本
//            originalAttributedStr.replaceCharactersInRange(range, withAttributedString: attributedStr)
//            //指定富文本字体大小
//            originalAttributedStr.addAttribute(NSFontAttributeName, value: textView.font!, range:NSMakeRange(0,originalAttributedStr.length))
//            //设置富文本显示数据
//            textView.attributedText = originalAttributedStr
//            //每次点击让其光标向后移动一个位置,并让其选中的范围为0
//            range.location += 1; range.length = 0
//            //根据选中的范围 设置光标的位置
//            textView.selectedRange = range
//            //发送通知 让表情按钮被点击的时候 实现类似textView.hasText 效果
//            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
//            //使导航栏发送按钮调用
//            //通过代理对象调用文字改变的函数
//            textView.delegate?.textViewDidChange!(textView)
//        }else {
//            //emoji文字
//            let emoji = (emoicon.code! as NSString).emoji()
//            textView.insertText(emoji)
//        }
    }
    
    //取消按钮点击事件
    @objc private func cancelAction(){
        self.view.endEditing(true )
        dismissViewControllerAnimated(true , completion: nil)
    }
    /*
    
    发送微博
    1.发送文字微博
    2.发送带图片的微博 (只能发送一张图片)
    
    
    */
    
    @objc private func sendWeiboAction(){
        
        
        
        //带图片微博上传接口
        if pictureView.images.count > 0 {
            //每次上传  只能上传一张图片
            let image = pictureView.images.first!
            
            let accessToken = CLUserAccountViewModel.sharedUserAccount.accesstoken!
            let text = textView.emoiconString
            CLNetWorkingTool.sharedTool.upload(accessToken, status:text, image: image, callBack: { (response, error) -> () in
                if error != nil {
                
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    return
                }else {
                    SVProgressHUD.showSuccessWithStatus("发送成功")
                    
                }
            })
        }else {
            //发送文字微博
            let accessToken = CLUserAccountViewModel.sharedUserAccount.accesstoken!
            let text = textView.emoiconString
            SVProgressHUD.show()
            CLNetWorkingTool.sharedTool.update(accessToken, status: text, callBack: { (response, error) -> () in
                if error != nil {
                    print(error)
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发送成功")
            })
            
        }
    }
    
    
    
    // MARK:  移除通知
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}
//处理toolbar按钮点击的逻辑
extension CLComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func didSelectedEmoicon(){
        if textView.inputView == nil {
            //设置表情键盘
            textView.inputView = keyboard
            toolBar.showEmoiconButtonIcon(true)
            
        }else {
            textView.inputView = nil
            toolBar.showEmoiconButtonIcon(false)
        }
        
        //获取第一响应者
        textView.becomeFirstResponder()
        //重新刷新intputview
        textView.reloadInputViews()
        
    }
    
    
    
    
    func didSelectedPicture(){
        let imagePictureCtr = UIImagePickerController()
        //设置代理
        imagePictureCtr.delegate = self
        
        //判断是否支持来源类型
        if UIImagePickerController.isSourceTypeAvailable(.Camera){
            print("支持相机")
        }else {
            imagePictureCtr.sourceType = .PhotoLibrary
            print("不支持相机,使用相册")
        }
        presentViewController(imagePictureCtr, animated: true , completion: nil)
        
    }
    //获取选中的图片  如果实现了协议  就不会自己调用dismiss
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        let scaleImage = scaleImageWithScaleWidth(200, image: image)
        pictureView.addImage(scaleImage)
        picker.dismissViewControllerAnimated(true , completion: nil)
    }
    //压缩图片  减少内存消耗
    private func scaleImageWithScaleWidth (scaleWidth:CGFloat,image:UIImage) ->UIImage {
        
        //根据压缩后的宽度来计算压缩后的高度
        let scaleHeight = scaleWidth / image.size.width * image.size.height
        //压缩后的大小
        let size = CGSize(width: scaleWidth, height: scaleHeight)
        //开启上下文
        UIGraphicsBeginImageContext(size)
        //吧图片渲染到指定范围
        image.drawInRect(CGRect(origin: CGPointZero, size: size))
        //获取上下文中压缩后的图片
        let scaleImage = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        return scaleImage
    }
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true , completion: nil)
    }
}

extension CLComposeViewController:UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        //根据文本内容判断发送按钮是否可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}









